<template>
  <ElementDialog
    :title="title"
    custom-class="image-file-viewer"
    :body-padding="false"
    v-bind="$attrs"
    :visible="visible"
    height="60vh"
    show-full-screen
    embed
    @hook:mounted="show"
    v-on="$listeners">
    <template #default>
      <div ref="wrapper" style="display: none">
        <slot>
          <img
            v-for="(item, sIndex) in images"
            :key="`${item.src}_${sIndex}`"
            class="image-item"
            :style="{ backgroundImage: `url('${item.src}')` }"
            :data-src="item.src"
            :alt="item.alt" />
        </slot>
      </div>
      <ResizeObserver @notify="resize" />
    </template>
  </ElementDialog>
</template>

<script>
  import Viewer from 'viewerjs'
  import 'viewerjs/dist/viewer.css'
  import { toFileUrl } from '@/util/core'

  export default {
    name: 'ImageFileViewer',
    props: {
      visible: Boolean,
      file: Object,
      files: Array
    },
    data() {
      return {
        index: 0
      }
    },
    computed: {
      images() {
        return this.files
          ? this.files.map(value => ({
              src: toFileUrl(value)
            }))
          : []
      },
      title() {
        return `(${this.index + 1}/${this.files.length}) ${this.files[this.index].filename}`
      }
    },
    beforeDestroy() {
      this.gallery?.destroy()
    },
    methods: {
      init({ container, options }) {
        this.gallery = new Viewer(container, options)
      },
      resize() {
        this.gallery?.resize()
      },
      async show() {
        await this.$nextTick()
        const container = this.$refs.wrapper
        const options = {
          button: false,
          navbar: false,
          transition: false,
          backdrop: 'static',
          url: 'data-src',
          loop: false,
          inline: true,
          initialViewIndex: this.files.indexOf(this.file),
          hidden: () => {
            this.gallery.destroy()
            this.gallery = null
          },
          view: event => {
            this.index = event.detail.index
          }
        }

        if (!this.gallery) {
          this.init({
            container,
            options
          })
          this.gallery.show()
        }
      }
    }
  }
</script>

<style lang="scss">
  .image-file-viewer {
    .viewer-container.viewer-backdrop {
      width: 100% !important;
      height: 100% !important;
      background-color: #404040;
    }
  }
</style>
